import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:xin_he/utils/xin_he_toast.dart';
import 'package:xin_he/utils/xin_he_user_data.dart';
import 'xin_he_invite_friend_state.dart';
import 'package:flutter/material.dart';
class XinHeInviteFriendLogic extends GetxController {
  final XinHeInviteFriendState state = XinHeInviteFriendState();
  GlobalKey globalKey = GlobalKey();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    state.inviteCode.value = xinHeUserData.userDetailInfo.value?.code??'';
  }
  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();

  }


  Future<Uint8List?> takeScreenshot() async {
    try {
      RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
      ui.Image image = await boundary.toImage(pixelRatio: 3.0); // 调整分辨率以适应高像素密度设备
      ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      if (byteData != null) {
        Uint8List pngBytes = byteData.buffer.asUint8List();
        return pngBytes;
      }
    } catch (e) {
      print(e);
    }
    return null;
  }

  void saveScreenshot() async {
    Uint8List? screenshotBytes = await takeScreenshot();
    if (screenshotBytes != null) {
      final result = await ImageGallerySaver.saveImage(screenshotBytes);

      if(Platform.isIOS){
        if(result){
          XinHeToast.center('成功保存到相册中');
        }else{
          XinHeToast.center('保存失败');
        }
      }else{
        if(result != null){
          XinHeToast.center('成功保存到相册中');
        }else{
          XinHeToast.center('保存失败');
        }
      }
      // print(result); // 打印保存结果
    }
  }
}
